'use strict';
import DCStore from '../stores/DCStore';
import NotifyActions from './NotifyActions';
import {IdentityEmail, IdentityPhone,VerifChinese} from '../tools/validateTool';
export default class DCAction {

  constructor() {
    this.generateActions('objID','todayDC','setUsername','setLastDCNum','hideText','hideLoading','usersData','users','setRowID','setDCNum','isClick');
  }
  
   /*LendCloud---登录*/
      login(parmas){
            this.showLoading();
            var username;
            var password;
            if (parmas != undefined) {
                username = parmas.get('username').toString();
                password = parmas.get('password').toString();
            }
           
            var url = Common.dcbaseUrl+'login?username='+username+'&password='+password;
            fetch(url,{
                  method:'GET',
                  headers:Common.headers})
                .then((response) => {
                      return response.text();
                }).then((result) => {
                  return JSON.parse(result);
                })
                .then((result) => {
                      if(result&&result.code&&result.error){
                            this.showText(result.error,1);
                            console.log(result)
                      }else{
                            console.log(result)
                            this.setUsername(result)
                            nav.push({title:'Login'})
                      }
                })
                .catch((error) => {
                      console.error(error);
                });

            return false;
      }
      /*LendCloud---自动登录*/
      automaticLogin(parmas){
        console.log(parmas)
      	this.showLoading();
            var username;
            var password;
            if (parmas != undefined) {
                username = parmas.username.toString();
                password = parmas.password.toString();
            }
           
            var url = Common.dcbaseUrl+'login?username='+username+'&password='+password;
            fetch(url,{
                  method:'GET',
                  headers:Common.headers})
                .then((response) => {
                      return response.text();
                }).then((result) => {
                  return JSON.parse(result);
                })
                .then((result) => {
                      if(result&&result.code&&result.error){
                            this.showText(result.error,1);
                            console.log(result)
                      }else{
                            nav.push({title:'Login'})
                            console.log(result)
                            this.setUsername(result)
                      }
                })
                .catch((error) => {
                      console.error(error);
                });

            return false;
      }
       /*LendCloud---注册*/
      regist(user){
        this.showLoading();
        var username = JSON.parse(user)&& JSON.parse(user).username
       
            if(VerifChinese(user)){
                  this.showText(localizedStrings.wrong_format_chinese, 1);
                  return false;
            }

            if(username&&username.length>0&&!IdentityPhone(username)){
                  this.showText(localizedStrings.phone_wrong_format, 1);
                  return false;
            }

            var url = 'https://api.leancloud.cn/1.1/users';
            
            fetch(url,{
                  method:'POST',
                 headers:Common.headersStore,body:user})
                .then((response) => {
                      return response.text();
                }).then((result) => {
                  return JSON.parse(result);
                })
                .then((result) => {
                      if(result&&result.code&&result.error){
                            this.showText(result.error,1);
                            console.log(result)
                      }else{
                            this.showText('注册成功',1);
                            NotifyActions.notify('regist');
                            this.hideLoading(); 
                      }
                })
                .catch((error) => {
                      console.error(error);
                });
                console.log(url)
            return false;
      }
     
       /*LendCloud---创建对象*/
       addObj(parmas){
        this.isClick(true)
        console.log('---------创建对象---------')
       var url = Common.dcbaseUrl+'classes/dcNum';
            fetch(url,{
                 method:'POST',
                 headers:Common.headersStore,body:parmas})
                .then((response) => {
                      return response.text();
                }).then((result) => {
                  return JSON.parse(result);
                })
                .then((result) => {

                      if(result&&result.code&&result.error){
                            this.showText('点餐失败',1);
                            console.log(result)
                      }else{
                            console.log('成功')
                            console.log(result)
                            this.showText('点餐成功',1);
                            NotifyActions.notify('dcSucess',result.objectId);
                      }
                })
                .catch((error) => {

                      console.error(error);
                });

            return false;
      }
     
      /*LendCloud---根据用户查询本月点餐记录*/
       queryObj(str){

            this.showLoading();

            var year = new Date().getFullYear();
            var mon;
            if (str == 'nowMon') {
                mon = new Date().getMonth()+1;
            }else if('lastMon'){
                mon = new Date().getMonth();
            }
            
            if (mon < 10) {
              mon = '0'+mon
            };
            var date_a = year+'-'+mon+'-'+'01'
            var date_b = year+'-'+mon+'-'+'31' 

            fetch('https://api.leancloud.cn/1.1/classes/dcNum?where='+'{"name":{"$in":['+'"'+ALT.stores.DCStore.getState().rowID+'"'+']},"createdAt":{"$gte":{"__type":"Date","iso":'+'"'+date_a+"T00:00:00.000Z"+'"'+'},"$lt":{"__type":"Date","iso":'+'"'+date_b+"T00:00:00.000Z"+'"'+'}}}',{
                  method:'GET',
                headers:Common.headersStore})
                .then((response) => {
                      return response.text();
                }).then((result) => {
                  return JSON.parse(result);
                })

                .then((result) => {

                      if(result&&result.code&&result.error){
                            this.showText('加载失败',1);
                            console.log(result)
                            NotifyActions.notify('LoadingFailData',result);

                      }else{
                            if (str == 'nowMon') {
                                this.setDCNum(result)
                            }else if('lastMon'){
                               this.setLastDCNum(result)
                            }
                            
                        
                            this.hideLoading();
                      }
                     
                })
                .catch((error) => {
                      console.error(error);
                });

            return false;
      }

      /*LendCloud---查询用户点餐记录*/
       queryDCObj(){
            this.showLoading();

            var year = new Date().getFullYear();
            var mon = new Date().getMonth()+1;
            if (mon < 10) {
              mon = '0'+mon
            };
            var date_a = year+'-'+mon+'-'+'01'
            var date_b = year+'-'+mon+'-'+'31'          

            fetch('https://api.leancloud.cn/1.1/classes/dcNum?where='+'{"username":{"$in":['+'"'+ALT.stores.DCStore.getState().username+'"'+']},"createdAt":{"$gte":{"__type":"Date","iso":'+'"'+date_a+"T00:00:00.000Z"+'"'+'},"$lt":{"__type":"Date","iso":'+'"'+date_b+"T00:00:00.000Z"+'"'+'}}}',{
                  method:'GET',
                headers:Common.headersStore})
                .then((response) => {
                      return response.text();
                }).then((result) => {
                  return JSON.parse(result);
                })

                .then((result) => {
                     this.isClick(false)

                      if(result&&result.code&&result.error){
                            this.showText('加载失败',1);
                            console.log(result)
                                NotifyActions.notify('LoadingFailHome',result);                         
                           
                      }else{
                            this.objID(result)
                          
                            this.hideLoading();
                      }
                     
                })
                .catch((error) => {
                     this.isClick(false)
                      console.error(error);
                });

            return false;
      }
      /*LendCloud---查询今日点餐记录*/
       queryTodayObj(){
            this.showLoading();

            var year = new Date().getFullYear();
            var mon = new Date().getMonth()+1;
            var day_a = new Date().getDate()-1
            var day_b = new Date().getDate()+1
            if (mon < 10) {
              mon = '0'+mon
            };
            if (day_a < 10) {
              day_a='0'+day_a
            }; 
            var date_a = year+'-'+mon+'-'+day_a
            var date_b = year+'-'+mon+'-'+day_b          
            fetch('https://api.leancloud.cn/1.1/classes/dcNum?where='+'{"createdAt":{"$gte":{"__type":"Date","iso":'+'"'+date_a+"T00:00:00.000Z"+'"'+'},"$lt":{"__type":"Date","iso":'+'"'+date_b+"T00:00:00.000Z"+'"'+'}}}',{
                  method:'GET',
                headers:Common.headersStore})
                .then((response) => {
                      return response.text();
                }).then((result) => {
                  return JSON.parse(result);
                })

                .then((result) => {
                     this.isClick(false)

                      if(result&&result.code&&result.error){
                            this.showText('加载失败',1);
                            console.log(result)
                                NotifyActions.notify('LoadingFailHome',result);                            
                           
                      }else{
                            this.todayDC(result)
                          
                            this.hideLoading();
                      }
                     
                })
                .catch((error) => {
                     this.isClick(false)
                      console.error(error);
                });

            return false;
      }
  	  /*LendCloud---查询用户*/
       queryUsers(){
            this.showLoading();
            fetch('https://api.leancloud.cn/1.1/classes/_User',{
                  method:'GET',
                headers:Common.headersStore})
                .then((response) => {
                      return response.text();
                }).then((result) => {
                  return JSON.parse(result);
                })

                .then((result) => {
                      if(result&&result.code&&result.error){
                          NotifyActions.notify('LoadingFailUsers',result);
                      }else{

                            this.users(result.results)
                   
                      }
                      this.hideLoading();
                     
                })
                .catch((error) => {
                      console.error(error);
                });

            return false;
      }
  	  /*LendCloud---删除对象*/
       delObj(parmas){
        this.isClick(true)
        this.showLoading();
        console.log('---------删除对象---------')

        if (parmas.get('type') == '0') {
        	ALT.stores.DCStore.getState().numLunch.pop()
        }else if (parmas.get('type') == '1') {
        	ALT.stores.DCStore.getState().numSupper.pop()
        };
        
       	var url = 'https://leancloud.cn:443/1.1/classes/dcNum/'+parmas.get('objId');
            fetch(url,{
                 method:'DELETE',
                 headers:Common.headersStore})
                .then((response) => {
                      return response.text();
                }).then((result) => {
                  return JSON.parse(result);
                })
                .then((result) => {
                      if(result&&result.code&&result.error){
                            this.showText('取消点餐失败',1);
                            console.log('删除失败')
                            console.log(result)
                      }else{
                            console.log('删除成功')
                            console.log(result)
                            this.showText('取消点餐成功',1);
                            NotifyActions.notify('delSucess',result);
                      }
                })
                .catch((error) => {

                      console.error(error);
                });

            return false;
      }

      showText(text, duration){
        if (duration != undefined) {

            setTimeout(this.hideText, duration*1000);
        }
        
        return {'text': text};
      }

      showLoading(duration){
    
        if (duration != undefined) {
            setTimeout(this.hideLoading, duration*1000);
        }

        return true;
      }

       /*LendCloud---更新对象*/
       /*updateObj(str){
        console.log('----------2222---------')
        var objectId = ALT.stores.DCStore.getState().objectId
        console.log('用户') 
        console.log(objectId) 
        var url = 'https://leancloud.cn:443/1.1/classes/dcNum/'+objectId;
        console.log(url)
            fetch(url,{
                 method:'PUT',
                 headers:Common.headersStore,body:str})
                .then((response) => {
                      return response.text();
                }).then((result) => {
                  return JSON.parse(result);
                })
                .then((result) => {
                      if(result&&result.code&&result.error){
                            MainActions.showText(result.error,1);
                            console.log(result)
                      }else{

                            console.log(result)
                            MainActions.showText('操作成功',1);
                      }
                })
                .catch((error) => {
                      console.error(error);
                });

            return false;
      }
*/
}
